const { app, BrowserWindow, dialog, ipcMain, globalShortcut, Tray, Menu, screen, shell } = require("electron")

const path = require("path")

let conf

require("./font.js")


// const path = require("path")


//读取csln-config.json文件

// ---- 启动express服务



let tray
let mainWindow
const createWindow = () => {
    mainWindow = new BrowserWindow({
        width: 1000,
        height: 600,
        minWidth: 800,
        minHeight: 400,
        title: "码语库记",
        icon: "icon.png",
        webPreferences: {
            nodeIntegration: true, // 允许使用node
            contextIsolation: false, // 允许使用contextBridge
            enableRemoteModule: true, // 允许使用remote
        }
    })

    // 加载vite环境变量
    if (process.env.VITE_DEV_SERVER_URL) {
        mainWindow.loadURL(process.env.VITE_DEV_SERVER_URL)
    } else {
        mainWindow.loadFile("dist/index.html")
    }
    // 打开开发者工具
    //mainWindow.webContents.openDevTools()
    // 取消Menu
    mainWindow.setMenu(null)

    // 监听关闭事件
    mainWindow.on("close", (event) => {
        event.preventDefault()
        mainWindow.hide()
    })




}



// 监听事件
app.whenReady().then(() => {
    // 初始化配置文件
    conf = require("./config.js")
    conf.init().then(() => {
        require("./config-event.js")
        require("./memo-evevt.js")


        createWindow()
        tray = new Tray(path.join(__dirname, "../icon.png"))
        tray.setToolTip("码语库记")
        tray.on("click", () => {
            toogleWin()
        })

        tray.on("right-click", () => {
            // 右键菜单
            tray.popUpContextMenu(Menu.buildFromTemplate([
                {
                    label: "退出",
                    click() {
                        app.quit()
                        setTimeout(() => {
                            app.exit()
                        }, 100)
                    }
                }, {
                    label: "打开主界面",
                    click() {
                        if (mainWindow.isVisible()) {
                            toogleWin()
                        } else {
                            mainWindow.show()
                        }
                    }
                },
                {
                    label: "官网",
                    click() {
                        shell.openExternal('https://csln.pages.dev/')
                    }
                },
                {
                    label: "调试",
                    click() {
                        mainWindow.webContents.openDevTools()
                    }
                }
            ]))
        })


        const express = require('express');
        const multer = require('multer');
        const cors = require('cors');
        const apps = express();
        const port = 34787;

        // 跨域设置
        apps.use(cors());



        // 设置存储引擎
        const storage = multer.diskStorage({ // 文件存储路径
            destination: (req, file, cb) => {// 文件存储路径
                cb(null, conf.config().note_path + "\\img"); // 指定文件存储路径
            },
            filename: (req, file, cb) => { // 文件名
                cb(null, Date.now() + path.extname(file.originalname)); // 指定文件名
            }
        });

        // 初始化上传
        const upload = multer({ storage: storage });

        // 静态文件服务
        apps.get('/:name', (req, res) => {
            // 获取请求的参数
            const name = req.params.name;
            // 读取文件
            res.sendFile(conf.config().note_path + "\\img\\" + name);
        });

        // 文件上传路由
        apps.post('/upload', upload.single('file'), (req, res) => {
            // Vditor 需要返回一个 JSON 响应，包含文件的 URL
            if (req.file) {
                res.json({
                    msg: "ok",
                    code: 0,
                    data: {
                        succMap: {
                            [req.file.originalname]: `http://localhost:${port}/${req.file.filename}`
                        }
                    }
                });
                console.log(req.file);
            } else {
                log.error('No file uploaded');
                res.status(400).json({ error: 'No file uploaded' });
            }
        });

        // 启动服务器
        apps.listen(port, () => {
            console.log(`Server is running at http://localhost:${port}`);
        });
    })

    // 检查更新
    if (conf.config().setting.auto_update) {// 自动更新
        let url = conf.config().warehouse.latest_release;
        // 向仓库获取最新版本
        fetch(url).then((res) => {
            return res.json();
        }).then(data => {
            if (data.tag_name != app.getVersion()) {
                // 弹出更新提示
                dialog.showMessageBox({
                    type: "info",
                    title: "更新提示",
                    message: `发现新版本${data.tag_name}，是否立即更新？\n将跳转至下载页面`,
                    buttons: ["确定", "取消"],
                }).then(res => {
                    if (res.response == 0) {
                        // 下载最新版
                        shell.openExternal("https://gitee.com/xiaowumin-mark/CodeSpeak-LibraryNotes/releases")
                    } else {
                        return
                    }
                })
            }

        })
    }

    const { creatMemoWindow } = require("./memo.js")
    //creatMemoWindow()

    globalShortcut.register("Alt+Shift+N", () => {
        creatMemoWindow()
    })


    ipcMain.on("get-mouse-loaction", (event, arg) => {
        event.reply("get-mouse-loaction", getCursorPixelPosition())
    })
    ipcMain.on("get-app-version", (e, d) => {
        let url = conf.config().warehouse.latest_release;
        // 向仓库获取最新版本
        fetch(url).then((res) => {
            return res.json();
        }).then(data => {
            let version = data.tag_name;
            e.reply("get-app-version", [app.getVersion(), version])
        }).catch(err => {
            e.reply("get-app-version", [app.getVersion(), "未知"])
        })
        
    })
})


app.on("will-quit", () => { // 监听退出事件
    globalShortcut.unregisterAll() // 注销快捷键
})
const toogleWin = () => {
    if (mainWindow.isVisible()) {
        mainWindow.hide()
    } else {
        mainWindow.show()
    }
}


function getCursorPixelPosition() {
    const cursorDIP = screen.getCursorScreenPoint();
    const displays = screen.getAllDisplays();
    // 假设鼠标位于第一个显示设备  
    const display = displays[0];
    if (display) {
        const scaleFactor = display.scaleFactor;
        const cursorPixel = {
            x: cursorDIP.x * scaleFactor,
            y: cursorDIP.y * scaleFactor
        };
        return cursorPixel;
    }
    return null; // 或其他错误处理  
}


